package cn.aigoubuy.web.servelt;

import cn.aigoubuy.domain.User;
import cn.aigoubuy.service.UserService;
import cn.aigoubuy.service.impl.UserServiceImpl;
import cn.aigoubuy.utils.CookieUtils;
import cn.aigoubuy.utils.MailUtils;
import cn.aigoubuy.utils.MyBeanUtils;
import cn.aigoubuy.utils.UUIDUtils;
import cn.aigoubuy.web.base.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/userServlet")
public class UserServlet extends BaseServlet {
    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("findAll");
    }

    /**
     * 跳转到注册页面
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String registUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        return "/jsp/register.jsp";
    }

    /**
     * 跳转到登录页面
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String loginUI(HttpServletRequest request, HttpServletResponse
            response)
            throws Exception {
        return "/jsp/login.jsp";
    }

    /**
     * 用户注册
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String regist(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 接收表单参数
        Map<String, String[]> map = request.getParameterMap();
        // 封装
        User user = MyBeanUtils.populate(User.class, map);
        // 为用户的其他属性赋值
        user.setUid(UUIDUtils.getId());
        user.setState(0); //未激活
        user.setCode(UUIDUtils.getCode());
        //System.out.println(user);
        // 调用业务层注册功能
        UserService userService = new UserServiceImpl();
        try {
            userService.regist(user);
            // 注册成功,向用户邮箱发送信息,跳转到提示页面
            // TODO 发送邮件
            MailUtils.sendMail2(user.getEmail(), user.getCode());
            request.setAttribute("msg", "用户注册成功,请激活!");
            //注册成功到登录页面
            return "/jsp/login.jsp";
        } catch (Exception e) {
            // 注册失败,跳转到提示页面
            request.setAttribute("msg", "用户注册失败,请重新注册!");
            return "/jsp/info.jsp";
        }
    }

    /**
     * 用户激活
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String active(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取激活码
        String code = request.getParameter("code");
        //调用业务层激活功能
        UserService UserService = new UserServiceImpl();
        boolean flag = UserService.activeUser(code);
        //进行激活信息提示
        if (flag) {
            //用户激活成功,向request放入提示信息,转发到登录页面
            request.setAttribute("msg", "用户激活成功,请登录!");
            return "/jsp/login.jsp";
        } else {
            //用户激活失败,向request放入提示信息,转发到提示页面
            request.setAttribute("msg", "用户激活失败,请重新激活!");
            return "/jsp/info.jsp";
        }
    }

    /**
     * 用户登录
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.获取用户数据(账户/密码)
        User user = MyBeanUtils.populate(User.class, request.getParameterMap());
        //2.调用业务层登录功能
        UserService userService = new UserServiceImpl();
        User loginUser = userService.login(user);
        if (loginUser != null) {
            // TODO 自动登录 start
            String autoLogin = request.getParameter("autoLogin");
            if("1".equals(autoLogin)) {
                // 勾选了
                Cookie autoLoginCookie = new Cookie("autoLoginCookie", user.getUsername()+"@"+user.getPassword());
                autoLoginCookie.setPath("/");
                autoLoginCookie.setMaxAge(60*60*24*7);
                response.addCookie(autoLoginCookie);
            } else {
                // 没有勾选 删除cookie
                Cookie autoLoginCookie = new Cookie("autoLoginCookie", "");
                autoLoginCookie.setPath("/");
                autoLoginCookie.setMaxAge(0);
                response.addCookie(autoLoginCookie);
            }
            // TODO 自动登录 end
            // TODO 记住用户名 start
            String rememberme = request.getParameter("rememberme");
            if("1".equals(rememberme)) {
                Cookie remembermeCookie = new Cookie("remembermeCookie",
                        user.getUsername());
                remembermeCookie.setPath("/");
                remembermeCookie.setMaxAge(60*60*24*7);
                response.addCookie(remembermeCookie);
            } else {
                //删除cookie
                Cookie remembermeCookie = new Cookie("autoLoginCookie", "");
                remembermeCookie.setPath("/");
                remembermeCookie.setMaxAge(0);
                response.addCookie(remembermeCookie);
            }
            // TODO 记住用户名 end
            //3.登录成功
            //select * from user where username=? and password=?
            // 用户登录成功,将用户信息放入session中
            request.getSession().setAttribute("loginUser", loginUser);
            //重定向到首页
            response.sendRedirect(request.getContextPath() + "/");
            return null;
        }
        // 4.登录失败
        //向request放入失败的信息
        request.setAttribute("msg", "用户名或密码不匹配或未激活");
        //请求转发到登录页
        return "/jsp/login.jsp";
    }

    /**
     * 退出
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 1.将session 用户状态清除
        request.getSession().removeAttribute("loginUser");
        //删除cookie
        Cookie remembermeCookie = new Cookie("autoLoginCookie", "");
        remembermeCookie.setPath("/");
        remembermeCookie.setMaxAge(0);
        response.addCookie(remembermeCookie);
        // 2.重新定向到首页
        response.sendRedirect(request.getContextPath() + "/index.jsp");
        // 3.不使用BaseServlet的请求转发
        return null;
    }

    /**
     * 异步校验用户名
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void checkUsername(HttpServletRequest req,HttpServletResponse resp) throws Exception,IOException {
        //接收文本框的值
        String username = req.getParameter("username");
        //调用业务层查询
        UserService userService = new UserServiceImpl();
        User existUser = userService.findByUsername(username);
        //判断
        if (existUser == null) {
            // 用户名可用
            resp.getWriter().println(1);
        } else {
            // 用户名已被占用
            resp.getWriter().println(2);
        }
    }
}